import Vue from 'vue'
import VueRouter from 'vue-router'
import HomeView from '../views/Home.vue'
import store from '@/store'

Vue.use(VueRouter)

//获取原型对象上的push函数
const originalPush = VueRouter.prototype.push
//修改原型对象中的push方法
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

const routes = [
  {
    path: '/',
    redirect: "/home",
  },
  {
    path: '/home',
    name: 'home',
    component: HomeView
  },
  {
    path: '/goods',
    name: 'goods',
    component: () => import('../views/Goods.vue')
  },
  {
    path: '/user',
    name: 'user',
    component: () => import('../views/User.vue'),
    redirect: "/user/cart",
    children: [
      {
        path: "cart",
        component: () => import('@/components/user/Cart.vue'),
      }
    ]
  },
  {
    path: '/order',
    name: 'order',
    component: () => import('../views/Order.vue'),
    beforeEnter: (to, from, next) => {
      console.log("路由独享守卫/order订单的", to, from,);
      let token = localStorage.getItem("x-auth-token")
      if (!token) {
        store.dispatch("showToast/asyncShowToast", {
          show: true,
          tType: "warning",
          tMsg: "请先登录！",
        })
        store.commit("showModel/changeIsShowLoginModel", true)
        return
      }
      next()
      // 返回 false 以取消导航
      return; // 需要些return，防止执行完上面的next()，还继续执行下面的next()
    }
  },
  {
    path: '/free',
    name: 'free',
    component: () => import('../views/Free.vue')
  },
  {
    path: '/details',
    name: 'details',
    component: () => import('../components/Details.vue')
  },
  {
    path: '/*',
    name: '*',
    component: () => import('../components/404Item.vue')
  },

]

const router = new VueRouter({
  // 不设 history 模式，默认的 hash 有页面无刷新的特点，网页不整体不刷新，通用的 Topbar 组件就不会重新创建，也就触发不了 created()，导致拿到的永远都是刚创建完的页面和 $route.query.code,拿不到扫完码后的 $route.query.code
  mode: "history",
  routes
})

// 全局守卫
router.beforeEach((to, from, next) => {
  console.log("全局守卫/user个人中心的", to, from);
  if (to.path == "/user") {
    let token = localStorage.getItem("x-auth-token")
    if (!token) {
      // alert("请先登录!")
      store.dispatch("showToast/asyncShowToast", {
        show: true,
        tType: "warning",
        tMsg: "请先登录！",
      })
      store.commit("showModel/changeIsShowLoginModel", true)
      return
    }
    next()
    // 返回 false 以取消导航
    return; // 需要些return，防止执行完上面的next()，还继续执行下面的next()
  }
  next() // 这个表示除 "/user" 外的路由继续往下执行
})

export default router
